import Vue from 'vue'
import ElDialog from 'element-ui/lib/dialog'
import ElButton from 'element-ui/lib/button'
import Message from 'element-ui/lib/message'

addCSS(`
    .el-dialog__body {
      padding-top: 0!important;
      padding-bottom: 0!important;
    }
    .no-title .el-dialog__header {
      padding:0px!important;
    }
  `)

let instance

export const openDialog = (params, parendDialog) => {
  let { componentProps, component, title, afterConfirm, afterCancel, buttonType, width } = params
  if (instance) {
    instance.$destroy()
    instance = null
  }
  
  if (!document.querySelector('#my-js-dialog')) {
    const el = document.createElement('div')
    el.id = 'my-js-dialog'
    document.body.appendChild(el)
  }
  instance = new Vue({
    el: document.querySelector('#my-js-dialog'),
    data() {
      return {
        visible: false,
        status: undefined
      }
    },
    methods: {
      confirm() {
        if (this.$refs.component.validate) {
          return this.$refs.component.validate().then((data) => {
            this.visible = false
            this.returnData = data
            this.status = 'success'
          }).catch((e) => {
            if (e && (typeof e === 'string' || e.message)) {
              Message({
                message: e.message || e
              })
            }
          })
        } else {
          this.visible = false
          this.returnData = null
          this.status = 'success'
        }
      }
    },
    watch: {
      visible(newValue, oldValue) {
        if (!newValue && oldValue) {
          instance.$destroy()
          instance = null
          if (this.status === 'success') {
            afterConfirm && afterConfirm(this.returnData)
          }
          if (this.status === 'cancel') {
            afterCancel && afterCancel()
          }
        }
      }
    },
    render(h) {
      let getButton = () => {
        if (buttonType === 'none') {
          return ''
        } else if (buttonType === 'detail') {
          return <div style="text-align:center;" slot="footer">
            <el-button size="small" type="primary" onClick={() => this.visible = false}>关闭</el-button>
          </div>
        } else {
          return <div style="text-align:center;" slot="footer">
            <el-button size="small" onClick={() => this.visible = false}>返回</el-button>
            <el-button size="small" type="primary" onClick={this.confirm} style="margin-left: 15px;">保存</el-button>
          </div>
        }
      }
      return h('el-dialog', {
        props: {
          width,
          center: false,
          title,
          customClass: title ? '' : 'no-title',
          appendToBody: true,
          visible: this.visible,
          closeOnClickModal: false
        },
        on: {
          'update:visible': (v) => {
            this.visible = v
          }
        }
      }, [
        h('dialog-component', {
          props: componentProps,
          attrs: componentProps,
          ref: 'component'
        }),
        getButton()
      ])
    },
    components: {
      ElDialog,
      ElButton,
      DialogComponent: component
    }
  })
  instance.visible = true
}

function addCSS(cssText) {
  if (!cssText) {
    return
  }
  var style = document.createElement('style') // 创建一个style元素
  var head = document.head || document.getElementsByTagName('head')[0] // 获取head元素
  style.type = 'text/css' // 这里必须显示设置style元素的type属性为text/css，否则在ie中不起作用
  if (style.styleSheet) { // IE
    var func = function () {
      try { // 防止IE中stylesheet数量超过限制而发生错误
        style.styleSheet.cssText = cssText
      } catch (e) {
      
      }
    }
    // 如果当前styleSheet还不能用，则放到异步中则行
    if (style.styleSheet.disabled) {
      setTimeout(func, 10)
    } else {
      func()
    }
  } else { // w3c
    // w3c浏览器中只要创建文本节点插入到style元素中就行了
    var textNode = document.createTextNode(cssText)
    style.appendChild(textNode)
  }
  head.appendChild(style) // 把创建的style元素插入到head中
}
